import "./index.css";

export function Progress(props) {
  let { dataList, width, completion } = props;
  let len = dataList.length;
  let lastData = dataList[len - 1];
	// 计算每一段的宽度，5个节点实际是4段
  let eWidth = width / (len - 1);
	// 找到最近一个比进度值大的节点索引
  let pIndex = dataList.findIndex((item) => {
    return item.num > completion;
  });
  let pWidth = width;
	// 判断不是最后一个
  if (pIndex > 0) {
		// 当前段的距离
    pWidth = (pIndex - 1) * eWidth;
		// 除第一个节点外，其余节点需要计算出前一个节点与完成度的大小，来判断是否需要增加50%的宽度
    let curNum = pIndex - 1 === 0 ? 0 : dataList[pIndex - 1].num;
    pWidth = curNum < completion ? pWidth + eWidth * 0.5 : pWidth;
  }

  return (
    <div className="p-content" style={{ width: width + "px" }}>
      <div className="c-container">
        <div className="c-swapper">
          <div className="progress" style={{ width: pWidth + "px" }}></div>
        </div>
      </div>

      <div className="c-main">
        {dataList.map(
          (item, index) =>
            index !== len - 1 && (
              <div className="m-item">
                <div className="line"></div>
                <div
                  className="main"
                  style={{
                    transform:
                      index !== 0 ? "translateX(-50%)" : "translateX(0)",
                    alignItems: index !== 0 ? "center" : "flex-start"
                  }}
                >
                  <div className="num">
                    {item.num}
                    {item.unit}
                  </div>
                  <div className="score">得{item.score}分</div>
                </div>
              </div>
            )
        )}
				{/* 这里将最后一个通过决定定位放到最后 */}
        <div className="m-last">
          <div className="line"></div>
          <div className="main l-main">
            <div className="num">
              {lastData.num}
              {lastData.unit}
            </div>
            <div className="score">得{lastData.score}分</div>
          </div>
        </div>
      </div>
    </div>
  );
}
